/*
 * @(#)SecurityConfig.java 2020-07-08
 *
 * Copyright (c) 2010 by rayootech.com. All rights reserved.
 */
package com.nuctech.formlogin.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

/**
 * @author lilu
 * @date 2020-07-08
 * @since 1.0.0
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Bean
	public PasswordEncoder passwordEncoder() {
		return NoOpPasswordEncoder.getInstance();
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication()
			.withUser("admin")
			.password("admin")
			.roles("admin");
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/js/**", "/css/**","/images/**");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
			.anyRequest().authenticated()
			.and()
			.formLogin()
			.loginPage("/login.html")
			.loginProcessingUrl("/doLogin")
			.usernameParameter("name")
			.passwordParameter("pass")
			// 重定向+记录前访问页面
			.defaultSuccessUrl("/index")
			// 服务器转发
//			.successForwardUrl("/index")
			// 重定向
			.failureUrl("/f1")
			// 服务器转发
//			.failureForwardUrl("/f2")
			.permitAll()
			.and()
			.logout()
			.logoutUrl("/logout")
//			.logoutRequestMatcher(new AntPathRequestMatcher("/logout","POST"))
			.deleteCookies()
			.clearAuthentication(true)
			.invalidateHttpSession(true)
			.permitAll()
			.and()
			.csrf().disable();
	}
}
